﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace RPGXEngine.Scripting.SystemFunctions
{
    public static class SystemFunction_FileAppendLine
    {
        public static IVariableType Method(ScriptManager sm, FunctionScope scope, List<IVariableType> data)
        {
            if (data == null || data.Count != 2)
                return sm.Zero;

            IVariableType res = sm.True;

            string fileName = data[0].Value.ToString();
            string content = data[1].Value.ToString();

            // TODO this should be in an IO helper file or something
            content = content.Replace("\\n", "\n");
            content = content.Replace("\\r", "\r");

            try
            {
                FileStream fp = File.Open(String.Format("{0}\\data\\{1}", Environment.CurrentDirectory, fileName),
                    FileMode.Append);

                StreamWriter writer = new StreamWriter(fp);
                writer.Write(content);

                writer.Close();
                fp.Close();
            }
            catch (Exception)
            {
                res = sm.False;
            }

            return res;
        }
    }
}
